package com.invest.utils.httpclient;

import com.squareup.okhttp.*;

import java.io.File;
import java.io.IOException;

public class OkHttpUtils {
	
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	
	/**
	 * POST JSON
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 */
	public static String postJson(String url, String json) throws IOException {
		
		OkHttpClient client = new OkHttpClient();
	 	RequestBody body = RequestBody.create(JSON, json);
	  	Request request = new Request.Builder()
	    .url(url)
	    .post(body)
	    .build();
	  	Response response = client.newCall(request).execute();
	   if(response.isSuccessful()) {
	    return response.body().string();
	  } else {
		  throw new IOException("Unexpected code " + response);
	  }
	}
	
	
	public static String postFile(String url,String formName,File file) throws IOException{
		
		final String boundary = "----------" + System.currentTimeMillis();
		final MediaType multipart = MediaType.parse("multipart/form-data;charset=utf-8;boundary="+boundary);
		OkHttpClient client = new OkHttpClient();
	 	RequestBody body = RequestBody.create(multipart, file);
	 	
	 	RequestBody requestBody = new MultipartBuilder()
        .type(MultipartBuilder.FORM)
        .addFormDataPart(formName,file.getName(),body)
        .build();
	 	
	 	
	 	Request request = new Request.Builder()
	    .url(url)
	    .post(requestBody)
	    .build();
	  	Response response = client.newCall(request).execute();
	   if(response.isSuccessful()) {
	    return response.body().string();
	  } else {
		  throw new IOException("Unexpected code " + response);
	  }
	}
}
